
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Http;

using U9BJWebApi.Models;
using System.Data;
using U9BJWebApi.Models.ReturnDTOs;
using U9BJWebApi.Models.RequestDTOs;
using System.Security.Cryptography;
using System.Web.Security;
using System.Data.SqlClient;

namespace U9BJWebApi.Controllers
{
	public class ReceiveController : ApiController
	{
		//public static string MESURL = System.Configuration.ConfigurationManager.AppSettings["MESURL"].ToString();
		public static string connectionString = Decrypt(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString(), "ConnectionString");
		public static string TokenCheck = System.Configuration.ConfigurationManager.AppSettings["TokenCheck"].ToString();
		[HttpPost]
		public Result<string> ItemMasterToMESCallBack(CallBack item)
		{

			Result<string> rtn = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{item.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						rtn.code = 0;
						rtn.msg = "该token已失效";
						return rtn;
					}
				}
				else
				{
					rtn.code = 0;
					rtn.msg = "无效token";
					return rtn;
				}
			}
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({GuidToLongID()}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'', N'{JsonConvert.SerializeObject(item)}', N'ItemMasterToMESCallBack', '', 0,'{item.Token}');";

			DbHelperSQL.ExecuteSql(Rdsql, connectionString);
			//CallBack item = JsonConvert.DeserializeObject<CallBack>(data);
			//foreach (var item in CallBacks)
			//{
			try
			{
				DbHelperSQL.ExecuteSql("update Inter_ItemMasterBE set Status = " + (item.IsSuccess ? 3 : 4) + ",ErrorMessage ='" + (item.ErrorMessage == null ? "" : item.ErrorMessage.Replace("@", "").Replace("\'", "\'\'").Replace("\"", "\'\'")) + "'  where ERPPkid =" + item.Pkid, connectionString);
				//DbHelperSQL.ExecuteSql("update Inter_ItemMasterBE set Status = " + (item.IsSuccess ? 3 : 4) + "  where ERPPkid =" + item.Pkid, connectionString);
			}
			catch (Exception e)
			{
				rtn.code = -1;
				rtn.msg = e.Message;
			}
			//}
			return rtn;
		}

		[HttpPost]
		public Result<string> BOMToMESCallBack(CallBack item)
		{

			Result<string> rtn = new Result<string>();
			if (TokenCheck == "True")
			{

				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{item.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						rtn.code = 0;
						rtn.msg = "该token已失效";
						return rtn;
					}
				}
				else
				{
					rtn.code = 0;
					rtn.msg = "无效token";
					return rtn;
				}
			}
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({GuidToLongID()}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'', N'{JsonConvert.SerializeObject(item)}', N'BOMToMESCallBack', '', 0,'{item.Token}');";

			DbHelperSQL.ExecuteSql(Rdsql, connectionString);
			//CallBack item = JsonConvert.DeserializeObject<CallBack>(data);
			//foreach (var item in CallBacks)
			//{
			try
			{
				DbHelperSQL.ExecuteSql("update Inter_BOMComponentBE set Status = " + (item.IsSuccess ? 3 : 4) + ",ErrorMessage ='" + (item.ErrorMessage == null ? "" : item.ErrorMessage.Replace("@", "").Replace("\'", "\'\'").Replace("\"", "\'\'")) + "'  where ERPPkid =" + item.Pkid, connectionString);
				//DbHelperSQL.ExecuteSql("update Inter_BOMComponentBE set Status = " + (item.IsSuccess ? 3 : 4) + "  where ERPPkid =" + item.Pkid, connectionString);

			}
			catch (Exception e)
			{
				rtn.code = -1;
				rtn.msg = e.Message;
			}
			//}
			return rtn;
		}

		[HttpPost]
		public Result<string> MOToMESCallBack(CallBack item)
		{
			Result<string> rtn = new Result<string>();
			if (TokenCheck == "True")
			{

				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{item.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						rtn.code = 0;
						rtn.msg = "该token已失效";
						return rtn;
					}
				}
				else
				{
					rtn.code = 0;
					rtn.msg = "无效token";
					return rtn;
				}
			}
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({GuidToLongID()}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'', N'{JsonConvert.SerializeObject(item)}', N'MOToMESCallBack', '', 0,'{item.Token}');";

			DbHelperSQL.ExecuteSql(Rdsql, connectionString);
			//CallBack item = JsonConvert.DeserializeObject<CallBack>(data);
			//foreach (var item in CallBacks)
			//{
			try
			{
				DbHelperSQL.ExecuteSql("update Inter_MOBE set Status = " + (item.IsSuccess ? 3 : 4) + ",ErrorMessage ='" + (item.ErrorMessage == null ? "" : item.ErrorMessage.Replace("@", "").Replace("\'", "\'\'").Replace("\"", "\'\'")) + "'  where ERPPkid =" + item.Pkid, connectionString);
				//DbHelperSQL.ExecuteSql("update Inter_MOBE set Status = " + (item.IsSuccess ? 3 : 4) + "  where ERPPkid =" + item.Pkid, connectionString);

			}
			catch (Exception e)
			{
				rtn.code = -1;
				rtn.msg = e.Message;
			}
			//}
			return rtn;
		}

		[HttpPost]
		public Result<string> CreateCompleteRpt(CreateCompleteRptDTO it)
		{
			WriteLog("进入完工接口,组织" + it.Org, "HLMessge");
			Result<string> rtn = new Result<string>();
			if (TokenCheck == "True")
			{

				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						rtn.code = 0;
						rtn.msg = "该token已失效";
						return rtn;
					}
				}
				else
				{
					rtn.code = 0;
					rtn.msg = "无效token";
					return rtn;

				}
			}
			//WriteLog("进入完工报告接口", "HLMessge");
			string Json = JsonConvert.SerializeObject(new SelectQuartzTaskInfoDTO
			{
				jobId = "MES_U9_ISSUEDOCLINE"
			});

			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}

			if (string.IsNullOrEmpty(MESURL))
			{
				rtn.code = 0;
				rtn.msg = "未找到MES地址";
				return rtn;
			}
			WriteLog("完工接口,组织" + it.Org + "对应地址:" + MESURL, "HLMessge");
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'CreateCompleteRpt', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);

			try
			{
				WriteLog("完工接口,组织" + it.Org + "   请求地址:" + MESURL + "/api/app/default-quartz-task/quartz-task-info    报文:" + Json, "HLMessge");
				var data = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info", Json);

				WriteLog("完工接口,组织" + it.Org + "   待发列表报文:" + JsonConvert.SerializeObject(data), "HLMessge");
				if (!string.IsNullOrEmpty(data.rtnMsg))
				{

					List<rtnMsg> rtnMsgs = JsonConvert.DeserializeObject<List<rtnMsg>>(data.rtnMsg);
					var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{JsonConvert.SerializeObject(data.rtnMsg)}' where id ={rdid}";
					DbHelperSQL.ExecuteSql(Rdupsql, connectionString);

					List<RequestQuartzTaskHisInfoDto> results = new List<RequestQuartzTaskHisInfoDto>();
					foreach (var rtnMsg in rtnMsgs)
					{
						IssueDocLineDTOHead IssueDocLineDTOs = JsonConvert.DeserializeObject<IssueDocLineDTOHead>(rtnMsg.JobMsg);
						foreach (var IssueDocLineDTO in IssueDocLineDTOs.Body)
						{
							if ((IssueDocLineDTO.FactoryId == "2575" || IssueDocLineDTO.FactoryId == "2574" || IssueDocLineDTO.FactoryId == "2577") && IssueDocLineDTO.PubStr4 == "20" && IssueDocLineDTO.CreateDate.Hour >= 18)
							{
								string dateck = $"select ToDate from Base_AccountingPeriod where AccountingCalendar = 1002204180000404  and ToDate =  '{IssueDocLineDTO.CreateDate.Date}'";
								DataSet tokends = DbHelperSQL.Query(dateck, connectionString);
								if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
								{
									IssueDocLineDTO.CreateDate = IssueDocLineDTO.CreateDate.Date.AddDays(1);
								}

							}
							//if ((IssueDocLineDTO.FactoryId == "2575" || IssueDocLineDTO.FactoryId == "2574" || IssueDocLineDTO.FactoryId == "2577") && ((IssueDocLineDTO.PubStr4 == "20" && IssueDocLineDTO.CreateDate.Hour >= 18 && IssueDocLineDTO.CreateDate.Date >= Convert.ToDateTime("2024-03-25")) || (IssueDocLineDTO.CreateDate.Date >= Convert.ToDateTime("2024-03-26"))) && IssueDocLineDTO.CreateDate.Date < Convert.ToDateTime("2024-04-01"))
							//{

							//	IssueDocLineDTO.CreateDate = Convert.ToDateTime("2024-04-01");


							//}
							WriteLog("完工接口,组织" + it.Org + "   完工信息:" + JsonConvert.SerializeObject(IssueDocLineDTO), "HLMessge");
							//DataSet dpds = DbHelperSQL.Query($@"select a.id   from CBO_Department a 
							//                                                         left join Base_Organization b on b.id = a.Org
							//                                                         where a.Code = '{IssueDocLineDTO.PubStr3}' and b.Code = '{IssueDocLineDTO.FactoryId}'", connectionString);

							DataSet ds = DbHelperSQL.Query($@"select a.id  from Inter_CompRptBE a				
														where a.Barcode = '{IssueDocLineDTO.Barcode}'
														and isnull(a.DocNo,'')<>'' ", connectionString);
							//int num = Convert.ToInt32(ds.Tables[0].Rows[0]["num"].ToString());

							if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
							{
								WriteLog($"该生产订单{IssueDocLineDTO.Billno}序列号在U9里已经有对应完工报告", "HLMessge");
								var CompRptBEID = Convert.ToInt64(ds.Tables[0].Rows[0]["id"]);
								string sql = $@"UPDATE [dbo].[Inter_CompRptBE] SET [MESPkid] = {IssueDocLineDTO.Pkid},[OrgCode]=N'{IssueDocLineDTO.FactoryId}', [ModifiedOn]='{DateTime.Now}',[Barcode]='{IssueDocLineDTO.Barcode}',[MO]=N'{IssueDocLineDTO.Billno}',[CompleteQty]={IssueDocLineDTO.Qty},[State]='{IssueDocLineDTO.Status}',[Status]=2,[ErrorMessage]='该序列号在U9里已经有对应完工报告',
                                                    [ItemMaster]='{IssueDocLineDTO.MaterielId}',[ProductQty]={IssueDocLineDTO.PubInt1},[BusinessDate]='{IssueDocLineDTO.CreateDate}',[MOStartDate]='{IssueDocLineDTO.PubStr1}',[MOCompleteDate]='{IssueDocLineDTO.PubStr2}',[Department]='{IssueDocLineDTO.PubStr3}',[ClassesID]='{IssueDocLineDTO.PubStr4}',[BOMVersion]='{IssueDocLineDTO.PubStr5}',[MODocNO]='{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}',[TeamId]='{IssueDocLineDTO.TeamId}',[Remark]='{IssueDocLineDTO.Remark}'
                                                    where ID = {CompRptBEID}";
								WriteLog(sql, "HLMessge");
								DbHelperSQL.ExecuteSql(sql, connectionString);


							}
							else
							{
								//DataSet ckds = DbHelperSQL.Query($@"select DISTINCT isnull(b.LotParam,0) Lot,isnull(b.SnParam,0) itemSn,isnull(c.IsSerial,0) whsn from CBO_ItemMaster a
								//							left join CBO_InventoryInfo b on b.ItemMaster = a.id
								//							left join CBO_Wh c on c.id = b.Warehouse
								//							left join Base_Organization d on d.id = a.Org
								//                            left join CBO_BOMMaster bom on bom.ItemMaster = a.id and bom.BOMVersionCode = {(string.IsNullOrEmpty(IssueDocLineDTO.PubStr5) ? "bom.BOMVersionCode" : ("'" + IssueDocLineDTO.PubStr5 + "'"))}
								//							where a.Code = '{IssueDocLineDTO.MaterielId}' and d.Code = '{IssueDocLineDTO.FactoryId}' and bom.id is not null");
								DataSet ckds = DbHelperSQL.Query($@"select DISTINCT isnull(b.LotParam,0) Lot,isnull(b.SnParam,0) itemSn,isnull(c.IsSerial,0) whsn from CBO_ItemMaster a
															left join CBO_InventoryInfo b on b.ItemMaster = a.id
															left join CBO_Wh c on c.id = b.Warehouse
															left join Base_Organization d on d.id = a.Org
                                                            left join CBO_BOMMaster bom on bom.ItemMaster = a.id 
															where a.Code = '{IssueDocLineDTO.MaterielId}' and d.Code = '{IssueDocLineDTO.FactoryId}' and bom.id is not null");
								if (ckds.Tables.Count > 0 && ckds.Tables[0].Rows.Count > 0)
								{
									bool islot = Convert.ToInt64(ckds.Tables[0].Rows[0]["Lot"]) > 0 ? true : false;
									bool itemSn = Convert.ToInt64(ckds.Tables[0].Rows[0]["itemSn"]) > 0 ? true : false;
									bool whsn = Convert.ToBoolean(ckds.Tables[0].Rows[0]["whsn"]);
									bool isSn = (whsn && itemSn) ? true : false;
									if (isSn && islot)
									{
										DataSet barcodeck = DbHelperSQL.Query($@"select a.id  from Inter_CompRptBE a				
														where a.Barcode = '{IssueDocLineDTO.Barcode}' ", connectionString);


										if (barcodeck.Tables.Count > 0 && barcodeck.Tables[0].Rows.Count > 0 && barcodeck.Tables[0].Rows[0]["id"] != null)
										{
											var CompRptBEID = Convert.ToInt64(barcodeck.Tables[0].Rows[0]["id"]);
											WriteLog($"该生产订单{IssueDocLineDTO.Billno}对应料品{IssueDocLineDTO.MaterielId}同时维护了批号管理与序列号管理,不能正常生成单据!", "HLMessge");
											string sql = $@"UPDATE [dbo].[Inter_CompRptBE] SET [MESPkid] = {IssueDocLineDTO.Pkid},[OrgCode]=N'{IssueDocLineDTO.FactoryId}', [ModifiedOn]='{DateTime.Now}',[Barcode]='{IssueDocLineDTO.Barcode}',[MO]=N'{IssueDocLineDTO.Billno}',[CompleteQty]={IssueDocLineDTO.Qty},[State]='{IssueDocLineDTO.Status}',[Status]=2,[ErrorMessage]='该生产订单对应料品同时维护了批号管理与序列号管理,不能正常生成单据!',
                                                    [ItemMaster]='{IssueDocLineDTO.MaterielId}',[ProductQty]={IssueDocLineDTO.PubInt1},[BusinessDate]='{IssueDocLineDTO.CreateDate}',[MOStartDate]='{IssueDocLineDTO.PubStr1}',[MOCompleteDate]='{IssueDocLineDTO.PubStr2}',[Department]='{IssueDocLineDTO.PubStr3}',[ClassesID]='{IssueDocLineDTO.PubStr4}',[BOMVersion]='{IssueDocLineDTO.PubStr5}',[MODocNO]='{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}',[TeamId]='{IssueDocLineDTO.TeamId}',[Remark]='{IssueDocLineDTO.Remark}'
                                                    where ID = {CompRptBEID}";
											WriteLog(sql, "HLMessge");
											DbHelperSQL.ExecuteSql(sql, connectionString);
										}
										else
										{
											WriteLog($"该生产订单{IssueDocLineDTO.Billno}对应料品{IssueDocLineDTO.MaterielId}同时维护了批号管理与序列号管理,不能正常生成单据!", "HLMessge");
											string sql = $@"INSERT INTO [dbo].[Inter_CompRptBE] ([ID],[MESPkid],[OrgCode], [CreatedOn],[Barcode],[MO],[CompleteQty],[State],[Status],[ErrorMessage],
                                                    [ItemMaster],[ProductQty],[BusinessDate],[MOStartDate],[MOCompleteDate],[Department],[ClassesID],[BOMVersion],[MODocNO],[TeamId],[Remark]) VALUES
                                                    ({GuidToLongID()},{IssueDocLineDTO.Pkid},N'{IssueDocLineDTO.FactoryId}', '{DateTime.Now}','{IssueDocLineDTO.Barcode}', N'{IssueDocLineDTO.Billno}',{IssueDocLineDTO.Qty},'{IssueDocLineDTO.Status}',2,'该生产订单对应料品同时维护了批号管理与序列号管理,不能正常生成单据!',
                                                     '{IssueDocLineDTO.MaterielId}', {IssueDocLineDTO.PubInt1},'{IssueDocLineDTO.CreateDate}','{IssueDocLineDTO.PubStr1}','{IssueDocLineDTO.PubStr2}','{IssueDocLineDTO.PubStr3}','{IssueDocLineDTO.PubStr4}','{IssueDocLineDTO.PubStr5}','{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}','{IssueDocLineDTO.TeamId}','{IssueDocLineDTO.Remark}' )";
											WriteLog(sql, "HLMessge");
											DbHelperSQL.ExecuteSql(sql, connectionString);
										}
									}
									else if (!isSn && !islot)
									{
										//string sql = "INSERT INTO [dbo].[Inter_CompRptBE] ([ID],[MESPkid],[OrgCode], [CreatedOn],[Barcode], [Department],[MO],[CompleteQty],[State],[Status],[ErrorMessage]) VALUES ({ GuidToLongID().ToString() + ",{ IssueDocLineDTO.Pkid + ",N'{ IssueDocLineDTO.FactoryId + "', '{ DateTime.Now + "','{ IssueDocLineDTO.Barcode + "',N'{ IssueDocLineDTO.ProductionLineId + "', N'{ IssueDocLineDTO.Billno + "',{ IssueDocLineDTO.Qty + ",'{ IssueDocLineDTO.Status + "',2,'该生产订单对应料品批号管理与序列号管理都未维护,不能正常生成单据!')";
										//DbHelperSQL.ExecuteSql(sql, connectionString);
										DataSet barcodeck = DbHelperSQL.Query($@"select a.id  from Inter_CompRptBE a				
														where a.Barcode = '{IssueDocLineDTO.Barcode}' ", connectionString);


										if (barcodeck.Tables.Count > 0 && barcodeck.Tables[0].Rows.Count > 0 && barcodeck.Tables[0].Rows[0]["id"] != null)
										{
											var CompRptBEID = Convert.ToInt64(barcodeck.Tables[0].Rows[0]["id"]);
											WriteLog($"该生产订单{IssueDocLineDTO.Billno}对应料品{IssueDocLineDTO.MaterielId}  非序列号 非批号", "HLMessge");
											string sql = $@"UPDATE [dbo].[Inter_CompRptBE] SET [MESPkid] = {IssueDocLineDTO.Pkid},[OrgCode]=N'{IssueDocLineDTO.FactoryId}', [ModifiedOn]='{DateTime.Now}',[Barcode]='{IssueDocLineDTO.Barcode}',[MO]=N'{IssueDocLineDTO.Billno}',[CompleteQty]={IssueDocLineDTO.Qty},[State]='{IssueDocLineDTO.Status}',[Status]=0,[ErrorMessage]='',
                                                    [ItemMaster]='{IssueDocLineDTO.MaterielId}',[ProductQty]={IssueDocLineDTO.PubInt1},[BusinessDate]='{IssueDocLineDTO.CreateDate}',[MOStartDate]='{IssueDocLineDTO.PubStr1}',[MOCompleteDate]='{IssueDocLineDTO.PubStr2}',[Department]='{IssueDocLineDTO.PubStr3}',[ClassesID]='{IssueDocLineDTO.PubStr4}',[BOMVersion]='{IssueDocLineDTO.PubStr5}',[MODocNO]='{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}',[TeamId]='{IssueDocLineDTO.TeamId}',[Remark]='{IssueDocLineDTO.Remark}'
                                                    where ID = {CompRptBEID}";
											WriteLog(sql, "HLMessge");
											DbHelperSQL.ExecuteSql(sql, connectionString);
										}
										else
										{
											WriteLog($"该生产订单{IssueDocLineDTO.Billno}对应料品{IssueDocLineDTO.MaterielId}  非序列号 非批号", "HLMessge");

											string sql = $@"INSERT INTO [dbo].[Inter_CompRptBE] ([ID],[MESPkid],[OrgCode], [CreatedOn],[Barcode],[MO],[CompleteQty],[State],[Status],
                                                    [ItemMaster],[ProductQty],[BusinessDate],[MOStartDate],[MOCompleteDate],[Department],[ClassesID],[BOMVersion],[MODocNO],[TeamId],[Remark]) VALUES
                                                  ({GuidToLongID().ToString()},{IssueDocLineDTO.Pkid},N'{IssueDocLineDTO.FactoryId}', '{DateTime.Now}','{IssueDocLineDTO.Barcode}', N'{IssueDocLineDTO.Billno}',{IssueDocLineDTO.Qty},'{IssueDocLineDTO.Status}',0,
                                                     '{IssueDocLineDTO.MaterielId}', {IssueDocLineDTO.PubInt1},'{IssueDocLineDTO.CreateDate}','{IssueDocLineDTO.PubStr1}','{IssueDocLineDTO.PubStr2}','{IssueDocLineDTO.PubStr3}','{IssueDocLineDTO.PubStr4}','{IssueDocLineDTO.PubStr5}','{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}','{IssueDocLineDTO.TeamId}','{IssueDocLineDTO.Remark}' )";
											WriteLog(sql, "HLMessge");
											DbHelperSQL.ExecuteSql(sql, connectionString);
										}
									}
									else if (isSn && !islot)
									{
										DataSet barcodeck = DbHelperSQL.Query($@"select a.id  from Inter_CompRptBE a				
														where a.Barcode = '{IssueDocLineDTO.Barcode}' ", connectionString);


										if (barcodeck.Tables.Count > 0 && barcodeck.Tables[0].Rows.Count > 0 && barcodeck.Tables[0].Rows[0]["id"] != null)
										{
											var CompRptBEID = Convert.ToInt64(barcodeck.Tables[0].Rows[0]["id"]);
											WriteLog($"该生产订单{IssueDocLineDTO.Billno}对应料品{IssueDocLineDTO.MaterielId}  序列号 非批号", "HLMessge");
											string sql = $@"UPDATE [dbo].[Inter_CompRptBE] SET [MESPkid] = {IssueDocLineDTO.Pkid},[OrgCode]=N'{IssueDocLineDTO.FactoryId}', [ModifiedOn]='{DateTime.Now}',[Barcode]='{IssueDocLineDTO.Barcode}',[MO]=N'{IssueDocLineDTO.Billno}',[CompleteQty]={IssueDocLineDTO.Qty},[State]='{IssueDocLineDTO.Status}',[Status]=0,[ErrorMessage]='',
                                                    [ItemMaster]='{IssueDocLineDTO.MaterielId}',[ProductQty]={IssueDocLineDTO.PubInt1},[BusinessDate]='{IssueDocLineDTO.CreateDate}',[MOStartDate]='{IssueDocLineDTO.PubStr1}',[MOCompleteDate]='{IssueDocLineDTO.PubStr2}',[Department]='{IssueDocLineDTO.PubStr3}',[ClassesID]='{IssueDocLineDTO.PubStr4}',[BOMVersion]='{IssueDocLineDTO.PubStr5}',[MODocNO]='{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}',[TeamId]='{IssueDocLineDTO.TeamId}',[Remark]='{IssueDocLineDTO.Remark}'
                                                    where ID = {CompRptBEID}";
											WriteLog(sql, "HLMessge");
											DbHelperSQL.ExecuteSql(sql, connectionString);
										}
										else
										{
											WriteLog($"该生产订单{IssueDocLineDTO.Billno}对应料品{IssueDocLineDTO.MaterielId}  序列号 非批号", "HLMessge");
											string sql = $@"INSERT INTO [dbo].[Inter_CompRptBE] ([ID],[MESPkid],[OrgCode], [CreatedOn],[Barcode],[MO],[CompleteQty],[State],[Status],
                                                    [ItemMaster],[ProductQty],[BusinessDate],[MOStartDate],[MOCompleteDate],[Department],[ClassesID],[BOMVersion],[MODocNO],[TeamId],[Remark]) VALUES
                                                  ({GuidToLongID().ToString()},{IssueDocLineDTO.Pkid},N'{IssueDocLineDTO.FactoryId}', '{DateTime.Now}','{IssueDocLineDTO.Barcode}', N'{IssueDocLineDTO.Billno}',{IssueDocLineDTO.Qty},'{IssueDocLineDTO.Status}',0,
                                                     '{IssueDocLineDTO.MaterielId}', {IssueDocLineDTO.PubInt1},'{IssueDocLineDTO.CreateDate}','{IssueDocLineDTO.PubStr1}','{IssueDocLineDTO.PubStr2}','{IssueDocLineDTO.PubStr3}','{IssueDocLineDTO.PubStr4}','{IssueDocLineDTO.PubStr5}','{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}','{IssueDocLineDTO.TeamId}','{IssueDocLineDTO.Remark}' )";
											WriteLog(sql, "HLMessge");
											DbHelperSQL.ExecuteSql(sql, connectionString);
										}
									}
									else if (!isSn && islot)
									{
										DataSet barcodeck = DbHelperSQL.Query($@"select a.id  from Inter_CompRptBE a				
														where a.Barcode = '{IssueDocLineDTO.Barcode}' ", connectionString);


										if (barcodeck.Tables.Count > 0 && barcodeck.Tables[0].Rows.Count > 0 && barcodeck.Tables[0].Rows[0]["id"] != null)
										{
											var CompRptBEID = Convert.ToInt64(barcodeck.Tables[0].Rows[0]["id"]);
											WriteLog($"该生产订单{IssueDocLineDTO.Billno}对应料品{IssueDocLineDTO.MaterielId}  非序列号 批号", "HLMessge");
											string sql = $@"UPDATE [dbo].[Inter_CompRptBE] SET [MESPkid] = {IssueDocLineDTO.Pkid},[OrgCode]=N'{IssueDocLineDTO.FactoryId}', [ModifiedOn]='{DateTime.Now}',[Barcode]='{IssueDocLineDTO.Barcode}',[MO]=N'{IssueDocLineDTO.Billno}',[CompleteQty]={IssueDocLineDTO.Qty},[State]='{IssueDocLineDTO.Status}',[Status]=0,[ErrorMessage]='',
                                                    [ItemMaster]='{IssueDocLineDTO.MaterielId}',[ProductQty]={IssueDocLineDTO.PubInt1},[BusinessDate]='{IssueDocLineDTO.CreateDate}',[MOStartDate]='{IssueDocLineDTO.PubStr1}',[MOCompleteDate]='{IssueDocLineDTO.PubStr2}',[Department]='{IssueDocLineDTO.PubStr3}',[ClassesID]='{IssueDocLineDTO.PubStr4}',[BOMVersion]='{IssueDocLineDTO.PubStr5}',[MODocNO]='{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}',[TeamId]='{IssueDocLineDTO.TeamId}',[Remark]='{IssueDocLineDTO.Remark}'
                                                    where ID = {CompRptBEID}";
											WriteLog(sql, "HLMessge");
											DbHelperSQL.ExecuteSql(sql, connectionString);
										}
										else
										{
											WriteLog($"该生产订单{IssueDocLineDTO.Billno}对应料品{IssueDocLineDTO.MaterielId}  非序列号 批号", "HLMessge");
											string sql = $@"INSERT INTO [dbo].[Inter_CompRptBE] ([ID],[MESPkid],[OrgCode], [CreatedOn],[Barcode],[MO],[CompleteQty],[State],[Status],
                                                    [ItemMaster],[ProductQty],[BusinessDate],[MOStartDate],[MOCompleteDate],[Department],[ClassesID],[BOMVersion],[MODocNO],[TeamId],[Remark]) VALUES
                                                  ({GuidToLongID().ToString()},{IssueDocLineDTO.Pkid},N'{IssueDocLineDTO.FactoryId}', '{DateTime.Now}','{IssueDocLineDTO.Barcode}', N'{IssueDocLineDTO.Billno}',{IssueDocLineDTO.Qty},'{IssueDocLineDTO.Status}',0,
                                                     '{IssueDocLineDTO.MaterielId}', {IssueDocLineDTO.PubInt1},'{IssueDocLineDTO.CreateDate}','{IssueDocLineDTO.PubStr1}','{IssueDocLineDTO.PubStr2}','{IssueDocLineDTO.PubStr3}','{IssueDocLineDTO.PubStr4}','{IssueDocLineDTO.PubStr5}','{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}','{IssueDocLineDTO.TeamId}','{IssueDocLineDTO.Remark}' )";
											WriteLog(sql, "HLMessge");
											DbHelperSQL.ExecuteSql(sql, connectionString);
										}
									}
									//string sql = "INSERT INTO [dbo].[Inter_CompRptBE] ([ID],[MESPkid],[OrgCode], [CreatedOn],[Barcode], [Department],[MO],[CompleteQty],[State],[Status]) VALUES ({ GuidToLongID().ToString() },{ IssueDocLineDTO.Pkid },N'{ IssueDocLineDTO.FactoryId }', '{ DateTime.Now }','{ IssueDocLineDTO.Barcode }',N'{ IssueDocLineDTO.ProductionLineId }', N'{ IssueDocLineDTO.Billno }',{ IssueDocLineDTO.Qty },'{ IssueDocLineDTO.Status }',0)";
									//                        DbHelperSQL.ExecuteSql(sql, connectionString);
								}
								else
								{
									DataSet barcodeck = DbHelperSQL.Query($@"select a.id  from Inter_CompRptBE a				
														where a.Barcode = '{IssueDocLineDTO.Barcode}' ", connectionString);


									if (barcodeck.Tables.Count > 0 && barcodeck.Tables[0].Rows.Count > 0 && barcodeck.Tables[0].Rows[0]["id"] != null)
									{
										var CompRptBEID = Convert.ToInt64(barcodeck.Tables[0].Rows[0]["id"]);
										WriteLog($"该生产订单{IssueDocLineDTO.Billno}找不到对应料品和BOM版本的BOM母项!", "HLMessge");
										string sql = $@"UPDATE [dbo].[Inter_CompRptBE] SET [MESPkid] = {IssueDocLineDTO.Pkid},[OrgCode]=N'{IssueDocLineDTO.FactoryId}', [ModifiedOn]='{DateTime.Now}',[Barcode]='{IssueDocLineDTO.Barcode}',[MO]=N'{IssueDocLineDTO.Billno}',[CompleteQty]={IssueDocLineDTO.Qty},[State]='{IssueDocLineDTO.Status}',[Status]=2,[ErrorMessage]='找不到对应料品和BOM版本的BOM母项!',
                                                    [ItemMaster]='{IssueDocLineDTO.MaterielId}',[ProductQty]={IssueDocLineDTO.PubInt1},[BusinessDate]='{IssueDocLineDTO.CreateDate}',[MOStartDate]='{IssueDocLineDTO.PubStr1}',[MOCompleteDate]='{IssueDocLineDTO.PubStr2}',[Department]='{IssueDocLineDTO.PubStr3}',[ClassesID]='{IssueDocLineDTO.PubStr4}',[BOMVersion]='{IssueDocLineDTO.PubStr5}',[MODocNO]='{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}',[TeamId]='{IssueDocLineDTO.TeamId}',[Remark]='{IssueDocLineDTO.Remark}'
                                                    where ID = {CompRptBEID}";
										WriteLog(sql, "HLMessge");
										DbHelperSQL.ExecuteSql(sql, connectionString);
									}
									else
									{
										WriteLog($"该生产订单{IssueDocLineDTO.Billno}找不到对应料品和BOM版本的BOM母项!", "HLMessge");

										string sql = $@"INSERT INTO [dbo].[Inter_CompRptBE] ([ID],[MESPkid],[OrgCode], [CreatedOn],[Barcode], [MO],[CompleteQty],[State],[Status],[ErrorMessage],
                                                    [ItemMaster],[ProductQty],[BusinessDate],[MOStartDate],[MOCompleteDate],[Department],[ClassesID],[BOMVersion],[MODocNO],[TeamId],[Remark]) VALUES
													 ({GuidToLongID().ToString()},{IssueDocLineDTO.Pkid},N'{IssueDocLineDTO.FactoryId}', '{DateTime.Now}','{IssueDocLineDTO.Barcode}', N'{IssueDocLineDTO.Billno}',{IssueDocLineDTO.Qty},'{IssueDocLineDTO.Status}',2,'找不到对应料品和BOM版本的BOM母项!',
                                                     '{IssueDocLineDTO.MaterielId}', {IssueDocLineDTO.PubInt1},'{IssueDocLineDTO.CreateDate}','{IssueDocLineDTO.PubStr1}','{IssueDocLineDTO.PubStr2}','{IssueDocLineDTO.PubStr3}','{IssueDocLineDTO.PubStr4}','{IssueDocLineDTO.PubStr5}','{(IssueDocLineDTO.Billno.Contains("-") ? IssueDocLineDTO.Billno : String.Empty)}','{IssueDocLineDTO.TeamId}','{IssueDocLineDTO.Remark}' )";
										WriteLog(sql, "HLMessge");
										DbHelperSQL.ExecuteSql(sql, connectionString);
									}
								}

							}


						}
						//CreateCompleteRptSV createCompleteRptSV = new CreateCompleteRptSV();
						//createCompleteRptSV.JobMsg = rtnMsg.JobMsg;
						//var bak = createCompleteRptSV.Do();
						//if (bak != "")
						//{
						results.Add(new RequestQuartzTaskHisInfoDto
						{
							factoryId = "",
							userNo = "",
							workcenterId = "",
							userToken = "",
							accountSets = "",
							dtoJsonStr = "",
							quartzTaskInfoDTO = new QuartzTaskInfoDTO
							{
								//jobId = rtnMsg.JobId,
								jobResult = "",
								taskPkid = rtnMsg.TaskPkid,
								quartzStatus = 1
							},
							quartzTaskLogInfoDto = new List<QuartzTaskLogInfoDto>() { new QuartzTaskLogInfoDto {
                                //jobId = rtnMsg.JobId,
                                taskDate = Convert.ToString(DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss"))
							} },
						}); ;

					


						//rtn.msg += (bak + ";");
						//rtn.code = 0;
						//}

					}

					SqlParameter[] paramater = { };
					DbHelperSQL.RunProcedure("SP_Cust_DistinctInterCompRptBE", paramater, "Table", connectionString);


					string UPDJson = JsonConvert.SerializeObject(results);

					var UPDrtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/upd-task-history-by-task", UPDJson);


				}
			}
			catch (Exception e)
			{

				WriteLog("完工接口  组织" + it.Org + "   报错信息：" + e.Message, "HLMessge");
			}

			return rtn;
		}

		public class CreateCompleteRptDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";

		}

		[HttpPost]
		public Result<string> CreateTransferDocAfterShipment(CreateTransferDocAfterShipmentDTO it)
		{

			Result<string> rtn = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						rtn.code = 0;
						rtn.msg = "该token已失效";
						return rtn;
					}
				}
				else
				{
					rtn.code = 0;
					rtn.msg = "无效token";
					return rtn;

				}
			}
			string Json = JsonConvert.SerializeObject(new SelectQuartzTaskInfoDTO
			{
				jobId = "MES_U9_SALEOUT"
			});
			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			if (string.IsNullOrEmpty(MESURL))
			{
				rtn.code = 0;
				rtn.msg = "未找到MES地址";
				return rtn;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'CreateTransferDocAfterShipment', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);
			string errormsg = string.Empty;
			var data = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info", Json);
			if (!string.IsNullOrEmpty(data.rtnMsg))
			{

				List<rtnMsg> rtnMsgs = JsonConvert.DeserializeObject<List<rtnMsg>>(data.rtnMsg);

				foreach (var rtnMsg in rtnMsgs)
				{
					SaleOutDTOHead SaleOutDTOs = JsonConvert.DeserializeObject<SaleOutDTOHead>(rtnMsg.JobMsg);





					//List<SOToShipDTO> SODTOList = new List<SOToShipDTO>();
					//List<SaleOutDTO> TransDtos = new List<SaleOutDTO>();

					foreach (var dto in SaleOutDTOs.Body)
					{
						DateTime BusinessDate = DateTime.Now;
						//if ((dto.FactoryId == "2575" || dto.FactoryId == "2574" || dto.FactoryId == "2577") && BusinessDate >= Convert.ToDateTime("2024-03-26") && BusinessDate < Convert.ToDateTime("2024-04-01"))
						//{
						//	BusinessDate = Convert.ToDateTime("2024-04-01");
						//}

						try
						{
							DataSet ckds = DbHelperSQL.Query($@"select isnull(b.SnParam,0) Sn from CBO_ItemMaster a
															left join CBO_InventoryInfo b on b.ItemMaster = a.id
															left join Base_Organization c on c.id = a.Org
															where a.Code = '{dto.Materielid}' and c.Code = '{dto.FactoryId}'");
							if (ckds.Tables.Count > 0 && ckds.Tables[0].Rows.Count > 0)
							{
								bool isSn = Convert.ToInt64(ckds.Tables[0].Rows[0]["Sn"]) > 0 ? true : false;

								if (isSn && string.IsNullOrEmpty(dto.Status))
								{
									DataSet shipck = DbHelperSQL.Query($@"select a.id  from Inter_ShipBE a				
														where a.MESPkid = {dto.Pkid} and a.Materielid = '{dto.Materielid}' and Status != 3 ", connectionString);


									if (shipck.Tables.Count > 0 && shipck.Tables[0].Rows.Count > 0 && shipck.Tables[0].Rows[0]["id"] != null)
									{
										var ShipBEID = Convert.ToInt64(shipck.Tables[0].Rows[0]["id"]);

										string sql = $@"UPDATE [dbo].[Inter_ShipBE] SET   [OrgCode] = {dto.FactoryId},  [Customer] = '{dto.CustomerId}',  [BusinessDate] = '{BusinessDate}', [ArcustomerId] = '{dto.ArcustomerId}',[Materielid] = '{dto.Materielid}', [MetricId] = '{dto.MetricId}', [Qty] = {dto.Qty}, [StoreroomId] = '{dto.StoreroomId}',[State] = '{dto.Status}', [Remark] = '{dto.MESBillno}', [BillType] = '{dto.BillType}', [CarNO] = '{dto.CarNO}',[SODocNo] = '{dto.Billno}',[ManageCode] = '{dto.Remark}' ,[Seller] = '{SaleOutDTOs.ID}'
													[Status] = 2, [ErrorMessage] = '该料品维护了序列号管理,请传输序列号',  
                                                    where ID = {ShipBEID}";
										WriteLog(sql, "HLMessge");
										DbHelperSQL.ExecuteSql(sql, connectionString);
									}
									else
									{
										var sql = @"INSERT INTO[dbo].[Inter_ShipBE] ([ID],[CreatedOn], [BusinessDate], [OrgCode],  [Customer],   [Status], [MESPkid], [ArcustomerId], [Materielid], [MetricId], [StoreroomId], [State],[Qty],[ErrorMessage],[BillType],[CarNO],[SODocNo],[ManageCode],[Remark],[Seller]) VALUES
											( '" + GuidToLongID().ToString() + "', '" + DateTime.Now + "', '" + BusinessDate + "','" + dto.FactoryId + "', N'" + dto.CustomerId + "', 2, '" + dto.Pkid + "', N'" + dto.ArcustomerId + "', N'" + dto.Materielid + "', N'" + dto.MetricId + "', N'" + dto.StoreroomId + "', N'" + dto.Status + "', " + dto.Qty + ",'该料品维护了序列号管理,请传输序列号','" + dto.BillType + "','" + dto.CarNO + "','" + dto.Billno + "','" + dto.Remark + "','" + dto.MESBillno + "','" + SaleOutDTOs.ID + "')";
										DbHelperSQL.ExecuteSql(sql, connectionString);
									}
								}
								else if (isSn && !string.IsNullOrEmpty(dto.Status) && dto.Qty != 1)
								{
									DataSet shipck = DbHelperSQL.Query($@"select a.id  from Inter_ShipBE a				
														where a.MESPkid = {dto.Pkid} and a.Materielid = '{dto.Materielid}' and Status != 3 ", connectionString);


									if (shipck.Tables.Count > 0 && shipck.Tables[0].Rows.Count > 0 && shipck.Tables[0].Rows[0]["id"] != null)
									{
										var ShipBEID = Convert.ToInt64(shipck.Tables[0].Rows[0]["id"]);

										string sql = $@"UPDATE [dbo].[Inter_ShipBE] SET   [OrgCode] = {dto.FactoryId},  [Customer] = '{dto.CustomerId}',  [BusinessDate] = '{BusinessDate}', [ArcustomerId] = '{dto.ArcustomerId}',[Materielid] = '{dto.Materielid}', [MetricId] = '{dto.MetricId}', [Qty] = {dto.Qty}, [StoreroomId] = '{dto.StoreroomId}',[State] = '{dto.Status}', [Remark] = '{dto.MESBillno}', [BillType] = '{dto.BillType}', [CarNO] = '{dto.CarNO}',[SODocNo] = '{dto.Billno}',[ManageCode] = '{dto.Remark}' ,[Seller] = '{SaleOutDTOs.ID}',
													[Status] = 2, [ErrorMessage] = '带序列号数据数量只能为1',  
                                                    where ID = {ShipBEID}";
										WriteLog(sql, "HLMessge");
										DbHelperSQL.ExecuteSql(sql, connectionString);
									}
									else
									{
										var sql = @"INSERT INTO[dbo].[Inter_ShipBE] ([ID],[CreatedOn], [BusinessDate], [OrgCode],  [Customer],   [Status], [MESPkid], [ArcustomerId], [Materielid], [MetricId], [StoreroomId], [State],[Qty],[ErrorMessage],[BillType],[CarNO],[SODocNo],[ManageCode],[Remark],[Seller]) VALUES
										    ( '" + GuidToLongID().ToString() + "', '" + DateTime.Now + "', '" + BusinessDate + "','" + dto.FactoryId + "', N'" + dto.CustomerId + "', 2, '" + dto.Pkid + "', N'" + dto.ArcustomerId + "', N'" + dto.Materielid + "', N'" + dto.MetricId + "', N'" + dto.StoreroomId + "', N'" + dto.Status + "', " + dto.Qty + ",'带序列号数据数量只能为1','" + dto.BillType + "','" + dto.CarNO + "','" + dto.Billno + "','" + dto.Remark + "','" + dto.MESBillno + "','" + SaleOutDTOs.ID + "')";
										DbHelperSQL.ExecuteSql(sql, connectionString);
									}
								}
								else
								{
									DataSet shipck = DbHelperSQL.Query($@"select a.id  from Inter_ShipBE a				
														where a.MESPkid = {dto.Pkid} and a.Materielid = '{dto.Materielid}' and Status != 3 ", connectionString);


									if (shipck.Tables.Count > 0 && shipck.Tables[0].Rows.Count > 0 && shipck.Tables[0].Rows[0]["id"] != null)
									{
										var ShipBEID = Convert.ToInt64(shipck.Tables[0].Rows[0]["id"]);

										string sql = $@"UPDATE [dbo].[Inter_ShipBE] SET   [OrgCode] = {dto.FactoryId},  [Customer] = '{dto.CustomerId}',  [BusinessDate] = '{BusinessDate}', [ArcustomerId] = '{dto.ArcustomerId}',[Materielid] = '{dto.Materielid}', [MetricId] = '{dto.MetricId}', [Qty] = {dto.Qty}, [StoreroomId] = '{dto.StoreroomId}',[State] = '{dto.Status}', [Remark] = '{dto.MESBillno}', [BillType] = '{dto.BillType}', [CarNO] = '{dto.CarNO}',[SODocNo] = '{dto.Billno}',[ManageCode] = '{dto.Remark}' ,[Seller] = '{SaleOutDTOs.ID}',
													[Status] = 0, [ErrorMessage] = '',  
                                                    where ID = {ShipBEID}";
										WriteLog(sql, "HLMessge");
										DbHelperSQL.ExecuteSql(sql, connectionString);
									}
									else
									{
										var sql = @"INSERT INTO[dbo].[Inter_ShipBE] ([ID],[CreatedOn], [BusinessDate], [OrgCode],  [Customer],   [Status], [MESPkid], [ArcustomerId], [Materielid], [MetricId], [StoreroomId], [State],[Qty],[BillType],[CarNO],[SODocNo],[ManageCode],[Remark],[Seller]) VALUES
											( '" + GuidToLongID().ToString() + "', '" + DateTime.Now + "', '" + BusinessDate + "','" + dto.FactoryId + "', N'" + dto.CustomerId + "', 0, '" + dto.Pkid + "', N'" + dto.ArcustomerId + "', N'" + dto.Materielid + "', N'" + dto.MetricId + "', N'" + dto.StoreroomId + "', N'" + dto.Status + "', " + dto.Qty + ",'" + dto.BillType + "','" + dto.CarNO + "','" + dto.Billno + "','" + dto.Remark + "','" + dto.MESBillno + "','" + SaleOutDTOs.ID + "')";
										DbHelperSQL.ExecuteSql(sql, connectionString);
									}
								}
							}
							else
							{
								DataSet shipck = DbHelperSQL.Query($@"select a.id  from Inter_ShipBE a				
														where a.MESPkid = {dto.Pkid} and a.Materielid = '{dto.Materielid}' and Status != 3 ", connectionString);


								if (shipck.Tables.Count > 0 && shipck.Tables[0].Rows.Count > 0 && shipck.Tables[0].Rows[0]["id"] != null)
								{
									var ShipBEID = Convert.ToInt64(shipck.Tables[0].Rows[0]["id"]);

									string sql = $@"UPDATE [dbo].[Inter_ShipBE] SET   [OrgCode] = {dto.FactoryId},  [Customer] = '{dto.CustomerId}',  [BusinessDate] = '{BusinessDate}', [ArcustomerId] = '{dto.ArcustomerId}',[Materielid] = '{dto.Materielid}', [MetricId] = '{dto.MetricId}', [Qty] = {dto.Qty}, [StoreroomId] = '{dto.StoreroomId}',[State] = '{dto.Status}', [Remark] = '{dto.MESBillno}', [BillType] = '{dto.BillType}', [CarNO] = '{dto.CarNO}',[SODocNo] = '{dto.Billno}',[ManageCode] = '{dto.Remark}' ,[Seller] = '{SaleOutDTOs.ID}',
													[Status] = 2, [ErrorMessage] = '未找到对应料品',  
                                                    where ID = {ShipBEID}";
									WriteLog(sql, "HLMessge");
									DbHelperSQL.ExecuteSql(sql, connectionString);
								}
								else
								{
									var sql = @"INSERT INTO[dbo].[Inter_ShipBE] ([ID],[CreatedOn], [BusinessDate], [OrgCode],  [Customer],   [Status], [MESPkid], [ArcustomerId], [Materielid], [MetricId], [StoreroomId], [State],[Qty],[ErrorMessage],[BillType],[CarNO],[SODocNo],[ManageCode],[Remark],[Seller]) VALUES
										    ( '" + GuidToLongID().ToString() + "', '" + DateTime.Now + "', '" + BusinessDate + "','" + dto.FactoryId + "', N'" + dto.CustomerId + "', 2, '" + dto.Pkid + "', N'" + dto.ArcustomerId + "', N'" + dto.Materielid + "', N'" + dto.MetricId + "', N'" + dto.StoreroomId + "', N'" + dto.Status + "', " + dto.Qty + ",'未找到对应料品','" + dto.BillType + "','" + dto.CarNO + "','" + dto.Billno + "','" + dto.Remark + "','" + dto.MESBillno + "','" + SaleOutDTOs.ID + "')";
									DbHelperSQL.ExecuteSql(sql, connectionString);
								}
							}
						}
						catch (Exception e)
						{
							errormsg += e.Message+";";
							continue;
						}
						//DataSet orgds = DbHelperSQL.Query("select top 1 id from Base_Organization where Code = '" + dto.FactoryId +"'");
						//var orgdt = orgds.Tables[0];
						//if (orgdt.Rows == null || orgdt.Rows.Count == 0)
						//{
						//	rtn.code = 0;
						//	rtn.msg = "未找到工厂" + dto.FactoryId;
						//	return rtn;
						//}
						//string orgId = orgdt.Rows[0]["id"].ToString();

						//DataSet SO1Typeds = DbHelperSQL.Query("select top 1 id from SM_SODocType where org = "+orgId+" and Code = 'SO1'");
						//DataTable SO1Typedt = SO1Typeds.Tables[0];
						//if (SO1Typedt.Rows == null || SO1Typedt.Rows.Count == 0)
						//{
						//	rtn.code = 0;
						//	rtn.msg = "未找到销售订单类型SO1";
						//	return rtn;
						//}
						//string SO1TypeID = SO1Typedt.Rows[0]["id"].ToString();

						//DataSet SOTypeds = DbHelperSQL.Query("select top 1 id from SM_SODocType where org = " + orgId + " and Code = 'SO'");
						//DataTable SOTypedt = SOTypeds.Tables[0];
						//if (SOTypedt.Rows == null || SOTypedt.Rows.Count == 0)
						//{
						//	rtn.code = 0;
						//	rtn.msg = "未找到销售订单类型SO";
						//	return rtn;
						//}
						//string SOTypeID = SOTypedt.Rows[0]["id"].ToString();

						//DataSet TransInTypeds = DbHelperSQL.Query("select top 1 id from InvDoc_TransInDocType where org = " + orgId + " and Code = 'TransIn002'");
						//DataTable TransInTypedt = TransInTypeds.Tables[0];
						//string TransInTypeID = TransInTypedt.Rows[0]["id"].ToString();


						//DataSet Itemmasterds = DbHelperSQL.Query("select top 1 id from CBO_Itemmaster where org = " + orgId + " and Code = '"+ dto.Materielid + "'");
						//DataTable Itemmasterdt = Itemmasterds.Tables[0];
						//if (Itemmasterdt.Rows == null || Itemmasterdt.Rows.Count == 0)
						//{
						//	rtn.code = 0;
						//	rtn.msg = "未找到物料"+ dto.Materielid;
						//	return rtn;
						//}
						//string ItemmasterId = Itemmasterdt.Rows[0]["id"].ToString();

						//DataSet Customerds = DbHelperSQL.Query("select top 1 id from CBO_Customer where org = " + orgId + " and Code = '" + dto.CustomerId + "'");
						//DataTable Customerdt = Customerds.Tables[0];
						//if (Customerdt.Rows == null || Customerdt.Rows.Count == 0)
						//{
						//	rtn.code = 0;
						//	rtn.msg = "未找到客户" + dto.CustomerId;
						//	return rtn;
						//}
						//string CustomerId = Customerdt.Rows[0]["id"].ToString();

						//DataSet CustomerSiteds = DbHelperSQL.Query("select top 1 id from CBO_CustomerSite where supplyorg = " + orgId + " and Code = '" + dto.ArcustomerId + "' and Customer = " + CustomerId);
						//DataTable CustomerSitedt = CustomerSiteds.Tables[0];
						//if (CustomerSitedt.Rows == null || CustomerSitedt.Rows.Count == 0)
						//{
						//	rtn.code = 0;
						//	rtn.msg = "未找到送达客户位置" + dto.ArcustomerId;
						//	return rtn;
						//}
						//string CustomerSiteId = CustomerSitedt.Rows[0]["id"].ToString();

						////DataSet Warehouseds = DbHelperSQL.Query("select top 1 id from CBO_Wh where org = " + orgId + " and Code = '" + dto.StoreroomId + "'");
						////DataTable Warehousedt = Warehouseds.Tables[0];
						////string WarehouseId = Warehousedt.Rows[0]["id"].ToString();


						//DataSet SO1Listds = DbHelperSQL.Query(@"select m.id as SOID,m.docno,l.id as SOLineID,
						//										l.DocLineNo ,s.code as SellerCode,l.OrderPriceTC,l.FinallyPriceTC,wh.code as WHCode	
						//										from SM_SO m
						//										left join SM_SOLine l on m.id = l.so
						//										left join CBO_Operators s  on s.id = m.Seller
						//										left join CBO_CustomerSite_Trl cs on cs.id = m.ShipToSite_CustomerSite
						//										left join CBO_Wh_Trl wht on wht.Name = cs.Name
						//										left join CBO_Wh wh on wh.id = wht.id
						//										where m.org = " + orgId + " and  m.DocumentType = " + SO1TypeID+ " and  m.orderby_customer = " + CustomerId + " and  m.Status = 3 and  m.ShipToSite_CustomerSite = " + CustomerSiteId + " and l.ItemInfo_ItemID = " + ItemmasterId);
						//DataTable SO1Listdt = SO1Listds.Tables[0];
						//for (int i = 0; i < SO1Listdt.Rows.Count; i++)
						//{
						//	long ship = GuidToLongID();
						//	DbHelperSQL.ExecuteSqlRtLong(@"INSERT INTO [dbo].[Inter_ShipBE] ([Id],[MESPkid],[OrgCode], [CreatedOn], [Customer], [Seller],[Status]) VALUES
						//							(" + ship + "," + dto.Pkid+",N'" + dto.FactoryId + "', '" + DateTime.Now + "', N'" + dto.CustomerId + "', '" + SO1Listdt.Rows[i]["SellerCode"].ToString() + "',0)");

						//	DbHelperSQL.ExecuteSql(@"INSERT INTO [dbo].[Inter_ShipLineBE] ([Id],[Ship],[CreatedOn],[ItemCode],[Qty],[OrderPriceTC],[FinallyPriceTC],[Wh]) VALUES
						//							(" + GuidToLongID().ToString() + "," + ship + ", '" + DateTime.Now + "', N'" + dto.Materielid + "', " + dto.Qty + "," + Convert.ToDecimal(SO1Listdt.Rows[i]["OrderPriceTC"].ToString()) + "," + Convert.ToDecimal(SO1Listdt.Rows[i]["FinallyPriceTC"].ToString()) + ",'" + SO1Listdt.Rows[i]["WHCode"].ToString() + "')");
						//}

						//DataSet SOListds = DbHelperSQL.Query(@"select m.id as SOID,m.docno,l.id as SOLineID,
						//										l.DocLineNo ,s.code as SellerCode,l.OrderPriceTC,l.FinallyPriceTC,wh.code as WHCode	
						//										from SM_SO m
						//										left join SM_SOLine l on m.id = l.so
						//										left join CBO_Operators s  on s.id = m.Seller
						//										left join CBO_CustomerSite_Trl cs on cs.id = m.ShipToSite_CustomerSite
						//										left join CBO_Wh_Trl wht on wht.Name = cs.Name
						//										left join CBO_Wh wh on wh.id = wht.id
						//										where m.org = " + orgId + " and  m.DocumentType = " + SOTypeID + " and  m.orderby_customer = " + CustomerId + " and  m.Status = 3 and  m.ShipToSite_CustomerSite = " + CustomerSiteId + " and l.ItemInfo_ItemID = " + ItemmasterId);
						//DataTable SOListdt = SOListds.Tables[0];
						//for (int i = 0; i < SOListdt.Rows.Count; i++)
						//{

						//	var dr = SOListdt.Rows[i];
						//	long TransferIn = GuidToLongID();
						//	 DbHelperSQL.ExecuteSqlRtLong(@"INSERT INTO [dbo].[Inter_NewTransferInBE] ([Id],[MESPkid],[OrgCode], [CreatedOn], [DocType], [TransferType],[BusinessDate],[Status],[CallBackType]) VALUES
						//							(" + TransferIn + "," + dto.Pkid + ",N'" + dto.FactoryId + "', '" + DateTime.Now + "', N'" + TransInTypeID + "', '1','" + DateTime.Now + "',0,2)");
						//	long TransferInLine = GuidToLongID();
						//	 DbHelperSQL.ExecuteSqlRtLong(@"INSERT INTO [dbo].[Inter_TransferInLineBE] ([Id],[TransferIn],  [ItemCode], [StoreUOMQty],[TransInWh],[StorageType]) VALUES
						//							(" + TransferInLine + "," + TransferIn + ", N'" + dto.Materielid + "', "+ dto.Qty + ",'" + dr["WHCode"].ToString() + "','4')");

						//	DbHelperSQL.ExecuteSql(@"INSERT INTO [dbo].[Inter_TransferInSubLineBE] ([Id],[TransferInLine],[TransOutWh],[StorageType],[StoreUOMQty]) VALUES
						//							(" + GuidToLongID().ToString() + "," + TransferInLine + ",N'" + dto.StoreroomId + "', 4 ," + dto.Qty + ")");

						//}

					}


					string UPDJson = JsonConvert.SerializeObject(new RequestQuartzTaskHisInfoDto
					{
						factoryId = "",
						userNo = "",
						workcenterId = "",
						userToken = "",
						accountSets = "",
						dtoJsonStr = "",
						quartzTaskInfoDTO = new QuartzTaskInfoDTO
						{
							//jobId = rtnMsg.JobId,
							jobResult = "",
							taskPkid = rtnMsg.TaskPkid,
							quartzStatus = 1
						},
						quartzTaskLogInfoDto = new List<QuartzTaskLogInfoDto>() { new QuartzTaskLogInfoDto {
                                //jobId = rtnMsg.JobId,
                                taskDate = Convert.ToString(DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss"))
							} },
					}); ;

					var UPDrtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-history-info-ins", UPDJson);


				}

				var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{errormsg + "报文:"+JsonConvert.SerializeObject(data.rtnMsg)}' where id ={rdid}";

				DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
			}
			return rtn;
		}

		public class CreateTransferDocAfterShipmentDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";
		}

		[HttpPost]
		public Result<string> CreatePullList(CreatePullListDTO it)
		{

			Result<string> rtn = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						rtn.code = 0;
						rtn.msg = "该token已失效";
						return rtn;
					}
				}
				else
				{
					rtn.code = 0;
					rtn.msg = "无效token";
					return rtn;

				}
			}
			List<rtnMsg> rtnMsgs = new List<rtnMsg>();
			string Json1 = JsonConvert.SerializeObject(new SelectQuartzTaskInfoDTO
			{
				jobId = "MES_U9_SEQPULL"
			});
			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			if (string.IsNullOrEmpty(MESURL))
			{
				rtn.code = 0;
				rtn.msg = "未找到MES地址";
				return rtn;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'CreatePullList', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);

			var data1 = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info", Json1);
			if (!string.IsNullOrEmpty(data1.rtnMsg))
			{
				rtnMsgs.AddRange(JsonConvert.DeserializeObject<List<rtnMsg>>(data1.rtnMsg));
			}
			string Json2 = JsonConvert.SerializeObject(new SelectQuartzTaskInfoDTO
			{
				jobId = "MES_U9_PLANSEQPULL"
			});
			var data2 = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info", Json2);
			if (!string.IsNullOrEmpty(data2.rtnMsg))
			{
				rtnMsgs.AddRange(JsonConvert.DeserializeObject<List<rtnMsg>>(data2.rtnMsg));
			}
			string Json3 = JsonConvert.SerializeObject(new SelectQuartzTaskInfoDTO
			{
				jobId = "MES_U9_KANBANPULL"
			});
			var data3 = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info", Json3);
			if (!string.IsNullOrEmpty(data3.rtnMsg))
			{
				rtnMsgs.AddRange(JsonConvert.DeserializeObject<List<rtnMsg>>(data3.rtnMsg));
			}
			string Json4 = JsonConvert.SerializeObject(new SelectQuartzTaskInfoDTO
			{
				jobId = "MES_U9_LOOPPULL"
			});
			var data4 = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info", Json4);
			if (!string.IsNullOrEmpty(data4.rtnMsg))
			{
				rtnMsgs.AddRange(JsonConvert.DeserializeObject<List<rtnMsg>>(data4.rtnMsg));
			}
			foreach (var rtnMsg in rtnMsgs)
			{
				MESPullDTOHead MESPullDTOs = JsonConvert.DeserializeObject<MESPullDTOHead>(rtnMsg.JobMsg);

				foreach (var MESPullDTO in MESPullDTOs.Body)
				{

					string sql = @"INSERT INTO [dbo].[Inter_PullListBE] ([ID],[MESPkid],[OrgCode], [CreatedOn], [ItemMaster],[RequireQty],[Supplier],[RequireType],[RequireDate],[WorkcenterId],[LineId],[Stockid],[Status]) 
									VALUES (" + GuidToLongID() + "," + MESPullDTO.Pkid + ",N'" + MESPullDTO.FactoryId + "', '" + DateTime.Now + "', N'" + MESPullDTO.MaterielId + "'," + MESPullDTO.RequireQty + ",'" + MESPullDTO.SupplierId + "','" + MESPullDTO.RequireType + "','" + MESPullDTO.RequireDate + "','" + MESPullDTO.WorkcenterId + "','" + MESPullDTO.LineId + "','" + MESPullDTO.Stockid + "',0)";
					DbHelperSQL.ExecuteSql(sql, connectionString);
				}
				//CreatePullListSV CreatePullListSV = new CreatePullListSV();
				//CreatePullListSV.JobMsg = rtnMsg.JobMsg;
				//var bak = CreatePullListSV.Do();
				//if (bak != "")
				//{
				string UPDJson = JsonConvert.SerializeObject(new RequestQuartzTaskHisInfoDto
				{
					factoryId = "",
					userNo = "",
					workcenterId = "",
					userToken = "",
					accountSets = "",
					dtoJsonStr = "",
					quartzTaskInfoDTO = new QuartzTaskInfoDTO
					{
						//jobId = rtnMsg.JobId,
						taskPkid = rtnMsg.TaskPkid,
						quartzStatus = 1
					},
					quartzTaskLogInfoDto = new List<QuartzTaskLogInfoDto>() { new QuartzTaskLogInfoDto {
                            //jobId = rtnMsg.JobId,
                            taskDate = Convert.ToString(DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss"))
						} },
				}); ;
				var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{UPDJson}' where id ={rdid}";

				DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
				var UPDrtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-history-info-ins", UPDJson);


				//	rtn.msg += (bak + ";");
				//	rtn.code = 0;
				//}
			}

			return rtn;
		}

		public class CreatePullListDTO
		{
			public string Org { get; set; }
			public string Token { get; set; } = "";
		}

		[HttpPost]
		public Result<string> CreateTransferDocAfterFix(CreateTransferDocAfterFixDTO it)
		{
			WriteLog("进入合格品不合格品调拨接口,组织" + it.Org, "HLMessge");
			Result<string> rtn = new Result<string>();
			if (TokenCheck == "True")
			{
				string tokenck = $"select DisableDate from Inter_MESToken where Code = '{it.Token}'";
				DataSet tokends = DbHelperSQL.Query(tokenck, connectionString);
				if (tokends.Tables.Count > 0 && tokends.Tables[0].Rows.Count > 0)
				{
					var DisableDate = Convert.ToDateTime(tokends.Tables[0].Rows[0]["DisableDate"]);
					if (DisableDate < DateTime.Now)
					{
						rtn.code = 0;
						rtn.msg = "该token已失效";
						return rtn;
					}
				}
				else
				{
					rtn.code = 0;
					rtn.msg = "无效token";
					return rtn;

				}
			}
			string Json = JsonConvert.SerializeObject(new SelectQuartzTaskInfoDTO
			{
				jobId = "MES_U9_TRANSALLOT"
			});

			string MESURL = "";
			string mesurlsql = $"select DescFlexField_PrivateDescSeg1 MESURL from Base_Organization where Code = '{it.Org}'";
			DataSet mesurlds = DbHelperSQL.Query(mesurlsql, connectionString);
			if (mesurlds.Tables.Count > 0 && mesurlds.Tables[0].Rows.Count > 0)
			{
				MESURL = mesurlds.Tables[0].Rows[0]["MESURL"].ToString();
			}
			WriteLog("合格品不合格品调拨接口,组织" + it.Org + "对应地址:" + MESURL, "HLMessge");
			if (string.IsNullOrEmpty(MESURL))
			{
				rtn.code = 0;
				rtn.msg = "未找到MES地址";
				return rtn;
			}
			long rdid = GuidToLongID();
			var Rdsql = $@"INSERT INTO [dbo].[Inter_MESRecordBE] ([ID], [CreatedOn], [ModifiedOn], [CreatedBy], [ModifiedBy], [URL], [Parameter], [API], [Message], [SysVersion],[Token]) 
														  VALUES ({rdid}, '{DateTime.Now}', '{DateTime.Now}', 'MES', N'MES', N'{MESURL}', N'{JsonConvert.SerializeObject(it)}', N'CreateTransferDocAfterFix', '', 0,'{it.Token}');";
			DbHelperSQL.ExecuteSql(Rdsql, connectionString);
			try
			{
				WriteLog("合格品不合格品调拨接口,组织" + it.Org + "   请求地址:" + MESURL + "/api/app/default-quartz-task/quartz-task-info    报文:" + Json, "HLMessge");
				var data = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-info", Json);
				WriteLog("合格品不合格品调拨接口,组织" + it.Org + "   待发列表报文:" + JsonConvert.SerializeObject(data), "HLMessge");

				if (!string.IsNullOrEmpty(data.rtnMsg))
				{

					List<rtnMsg> rtnMsgs = JsonConvert.DeserializeObject<List<rtnMsg>>(data.rtnMsg);
					var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{JsonConvert.SerializeObject(data.rtnMsg)}' where id ={rdid}";

					DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
					foreach (var rtnMsg in rtnMsgs)
					{
						TransDTOHead TransDTOs = JsonConvert.DeserializeObject<TransDTOHead>(rtnMsg.JobMsg);

						foreach (var dto in TransDTOs.Body)
						{
							DataSet ckds = DbHelperSQL.Query($@"select isnull(b.SnParam,0) Sn from CBO_ItemMaster a
															left join CBO_InventoryInfo b on b.ItemMaster = a.id
															left join Base_Organization c on c.id = a.Org														
															where a.Code = '{dto.MaterielId}' and c.Code = '{dto.FactoryId}'");
							if (ckds.Tables.Count > 0 && ckds.Tables[0].Rows.Count > 0)
							{
								bool isSn = Convert.ToInt64(ckds.Tables[0].Rows[0]["Sn"]) > 0 ? true : false;

								if (isSn && string.IsNullOrEmpty(dto.Barcode))
								{

									var sql = @"INSERT INTO[dbo].[Inter_NewTransferInBE] ([Id],[MESPkid],[OrgCode], [CreatedOn],  [TransferType],[BusinessDate],[Status],[Billno],[MaterielId],[Barcode],[State],[TargetStatus],[Qty],[ErrorMessage]) VALUES
									(" + GuidToLongID() + "," + dto.Pkid + ",N'" + dto.FactoryId + "', '" + DateTime.Now + "', '1','" + DateTime.Now + "',2,N'" + dto.Billno + "',N'" + dto.MaterielId + "',N'" + dto.Barcode + "',N'" + dto.Status + "',N'" + dto.TargetStatus + "'," + dto.Qty + ",'该料品维护了序列号管理,请传输序列号')";
									DbHelperSQL.ExecuteSql(sql, connectionString);

								}
								else if (isSn && !string.IsNullOrEmpty(dto.Barcode) && dto.Qty != 1)
								{
									var sql = @"INSERT INTO[dbo].[Inter_NewTransferInBE] ([Id],[MESPkid],[OrgCode], [CreatedOn],  [TransferType],[BusinessDate],[Status],[Billno],[MaterielId],[Barcode],[State],[TargetStatus],[Qty],[ErrorMessage]) VALUES
									(" + GuidToLongID() + "," + dto.Pkid + ",N'" + dto.FactoryId + "', '" + DateTime.Now + "', '1','" + DateTime.Now + "',2,N'" + dto.Billno + "',N'" + dto.MaterielId + "',N'" + dto.Barcode + "',N'" + dto.Status + "',N'" + dto.TargetStatus + "'," + dto.Qty + ",'带序列号数据数量只能为1')";
									DbHelperSQL.ExecuteSql(sql, connectionString);
								}
								else
								{
									var sql = @"INSERT INTO[dbo].[Inter_NewTransferInBE] ([Id],[MESPkid],[OrgCode], [CreatedOn],  [TransferType],[BusinessDate],[Status],[Billno],[MaterielId],[Barcode],[State],[TargetStatus],[Qty]) VALUES
									(" + GuidToLongID() + "," + dto.Pkid + ",N'" + dto.FactoryId + "', '" + DateTime.Now + "', '1','" + DateTime.Now + "',0,N'" + dto.Billno + "',N'" + dto.MaterielId + "',N'" + dto.Barcode + "',N'" + dto.Status + "',N'" + dto.TargetStatus + "'," + dto.Qty + ")";
									DbHelperSQL.ExecuteSql(sql, connectionString);
								}
							}

						}

						//DataSet orgds = DbHelperSQL.Query("select top 1 id from Base_Organization where Code = '" + TransDTOs.FirstOrDefault().FactoryId + "'");
						//var orgdt = orgds.Tables[0];
						//if (orgdt.Rows == null || orgdt.Rows.Count == 0)
						//{
						//	rtn.code = 0;
						//	rtn.msg = "未找到工厂" + TransDTOs.FirstOrDefault().FactoryId;
						//	return rtn;
						//}
						//string orgId = orgdt.Rows[0]["id"].ToString();

						//DataSet TransInTypeds = DbHelperSQL.Query("select top 1 id from InvDoc_TransInDocType where org = " + orgId + " and Code = 'TransIn002'");
						//DataTable TransInTypedt = TransInTypeds.Tables[0];
						//string TransInTypeID = TransInTypedt.Rows[0]["id"].ToString();

						//var UnQualifiedTransDTOs = TransDTOs.Where(m => m.Status == "合格" && m.TargetStatus == "不合格").ToList();
						//var QualifiedTransDTOs = TransDTOs.Where(m => m.Status == "不合格" && m.TargetStatus == "合格").ToList();


						////不合格
						//if (UnQualifiedTransDTOs.Count > 0)
						//{
						//	DataSet Warehouseds = DbHelperSQL.Query("select top 1 m.code from CBO_Wh m  left join CBO_Wh_Trl l on m.id = l.id  where m.org = " + orgId + " and l.Name  like '%成品（不合格仓）%'");
						//	DataTable Warehousedt = Warehouseds.Tables[0];
						//	string WarehouseCode = Warehousedt.Rows[0]["code"].ToString();

						//	foreach (var dto in UnQualifiedTransDTOs)
						//	{
						//		DataSet Itemmasterds = DbHelperSQL.Query("select top 1 id from CBO_Itemmaster where org = " + orgId + " and Code = '" + dto.MaterielId + "'");
						//		DataTable Itemmasterdt = Itemmasterds.Tables[0];
						//		string ItemmasterId = Itemmasterdt.Rows[0]["id"].ToString();

						//		//DataSet Warehouseoutds = DbHelperSQL.Query(@"select top 1 wh.code from  Sn_SnMaster sm
						//		//										left join Sn_SnBeUsed sb on sb.SnMaster = sm.id
						//		//										left join CBO_Wh wh on wh.id = sb.wh
						//		//										where sm.UsingOrg = " + orgId+ " and sm.sncode = '" + dto.Barcode + "' and sm.item = "+ ItemmasterId );
						//		DataSet Warehouseoutds = DbHelperSQL.Query(@"select top 1 wh.code from  Sn_SnMaster sm
						//												left join Sn_SnBeUsed sb on sb.SnMaster = sm.id
						//												left join CBO_Wh wh on wh.id = sb.wh
						//												where sm.UsingOrg = " + orgId + " and sm.sncode = '" + dto.Barcode + "'");
						//		DataTable Warehouseoutdt = Warehouseoutds.Tables[0];
						//		if (Warehouseoutdt.Rows.Count == 0) 
						//		{
						//			rtn.code = 0;
						//			rtn.msg = "序列号" + dto.Barcode +"未找到使用档";
						//			return rtn;
						//		}
						//		string WarehouseoutCode = Warehouseoutdt.Rows[0]["code"].ToString();

						//		long TransferIn = GuidToLongID();
						//		 DbHelperSQL.ExecuteSqlRtLong(@"INSERT INTO [dbo].[Inter_NewTransferInBE] ([Id],[MESPkid],[OrgCode], [CreatedOn], [DocType], [TransferType],[BusinessDate],[Status],[CallBackType]) VALUES
						//								(" + TransferIn + "," + dto.Pkid + ",N'" + dto.FactoryId + "', '" + DateTime.Now + "', N'" + TransInTypeID + "', '1','" + DateTime.Now + "',0,1)");
						//		long TransferInLine = GuidToLongID();
						//		DbHelperSQL.ExecuteSqlRtLong(@"INSERT INTO [dbo].[Inter_TransferInLineBE] ([Id],[TransferIn],  [ItemCode], [StoreUOMQty],[TransInWh],[StorageType]) VALUES
						//								(" + TransferInLine + "," + TransferIn + ", N'" + dto.MaterielId + "', " + dto.Qty + ",'" + WarehouseCode + "','4')");

						//		DbHelperSQL.ExecuteSql(@"INSERT INTO [dbo].[Inter_TransferInSubLineBE] ([Id],[TransferInLine],[TransOutWh],[StorageType],[StoreUOMQty]) VALUES
						//								(" + GuidToLongID().ToString() + "," + TransferInLine + ",N'" + WarehouseoutCode + "', 4 ," + dto.Qty + ")");
						//	}
						//}
						////合格
						//if (QualifiedTransDTOs.Count > 0)
						//{
						//	DataSet Warehouseds = DbHelperSQL.Query("select top 1 m.code from CBO_Wh m  left join CBO_Wh_Trl l on m.id = l.id  where m.org = " + orgId + " and l.Name  like '%成品库房%'");
						//	DataTable Warehousedt = Warehouseds.Tables[0];
						//	string WarehouseCode = Warehousedt.Rows[0]["code"].ToString();



						//	foreach (var dto in QualifiedTransDTOs)
						//	{

						//		DataSet Itemmasterds = DbHelperSQL.Query("select top 1 id from CBO_Itemmaster where org = " + orgId + " and Code = '" + dto.MaterielId + "'");
						//		DataTable Itemmasterdt = Itemmasterds.Tables[0];
						//		string ItemmasterId = Itemmasterdt.Rows[0]["id"].ToString();

						//		//DataSet Warehouseoutds = DbHelperSQL.Query(@"select top 1 wh.code from  Sn_SnMaster sm
						//		//										left join Sn_SnBeUsed sb on sb.SnMaster = sm.id
						//		//										left join CBO_Wh wh on wh.id = sb.wh
						//		//										where sm.UsingOrg = " + orgId + " and sm.sncode = '" + dto.Barcode + "' and sm.item = " + ItemmasterId);

						//		DataSet Warehouseoutds = DbHelperSQL.Query(@"select top 1 wh.code from  Sn_SnMaster sm
						//												left join Sn_SnBeUsed sb on sb.SnMaster = sm.id
						//												left join CBO_Wh wh on wh.id = sb.wh
						//												where sm.UsingOrg = " + orgId + " and sm.sncode = '" + dto.Barcode+"'");
						//		DataTable Warehouseoutdt = Warehouseoutds.Tables[0];
						//		if (Warehouseoutdt.Rows.Count == 0)
						//		{
						//			rtn.code = 0;
						//			rtn.msg = "序列号" + dto.Barcode + "未找到使用档";
						//			return rtn;
						//		}
						//		string WarehouseoutCode = Warehouseoutdt.Rows[0]["code"].ToString();

						//		long TransferIn = GuidToLongID();
						//		DbHelperSQL.ExecuteSqlRtLong(@"INSERT INTO [dbo].[Inter_NewTransferInBE] ([Id],[MESPkid],[OrgCode], [CreatedOn], [DocType], [TransferType],[BusinessDate],[Status],[CallBackType]) VALUES
						//								(" + TransferIn + "," + dto.Pkid + ",N'" + dto.FactoryId + "', '" + DateTime.Now + "', N'" + TransInTypeID + "', '1','" + DateTime.Now + "',0,1)");
						//		long TransferInLine = GuidToLongID();
						//		DbHelperSQL.ExecuteSqlRtLong(@"INSERT INTO [dbo].[Inter_TransferInLineBE] ([Id],[TransferIn],  [ItemCode], [StoreUOMQty],[TransInWh],[StorageType]) VALUES
						//								(" + TransferInLine + "," + TransferIn + ", N'" + dto.MaterielId + "', " + dto.Qty + ",'" + WarehouseCode + "','4')");

						//		DbHelperSQL.ExecuteSql(@"INSERT INTO [dbo].[Inter_TransferInSubLineBE] ([Id],[TransferInLine],[TransOutWh],[StorageType],[StoreUOMQty]) VALUES
						//								(" + GuidToLongID().ToString() + "," + TransferInLine + ",N'" + WarehouseoutCode + "', 4 ," + dto.Qty + ")");
						//	}
						//}
						//CreateTransferDocAfterFixSV CreateTransferDocAfterFixSV = new CreateTransferDocAfterFixSV();
						//CreateTransferDocAfterFixSV.JobMsg = rtnMsg.JobMsg;
						//var bak = CreateTransferDocAfterFixSV.Do();
						//if (bak != "")
						//{
						string UPDJson = JsonConvert.SerializeObject(new RequestQuartzTaskHisInfoDto
						{
							factoryId = "",
							userNo = "",
							workcenterId = "",
							userToken = "",
							accountSets = "",
							dtoJsonStr = "",
							quartzTaskInfoDTO = new QuartzTaskInfoDTO
							{
								//jobId = rtnMsg.JobId,
								taskPkid = rtnMsg.TaskPkid,
								quartzStatus = 1
							},
							quartzTaskLogInfoDto = new List<QuartzTaskLogInfoDto>() { new QuartzTaskLogInfoDto {
                                //jobId = rtnMsg.JobId,
                                taskDate = Convert.ToString(DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss"))
							} },
						}); ;
						//var Rdupsql = $@"Update [dbo].[Inter_MESRecordBE] set  Message = '{UPDJson}' where id ={rdid}";

						//DbHelperSQL.ExecuteSql(Rdupsql, connectionString);
						var UPDrtn = PostHelper.HttpPosts(MESURL + "/api/app/default-quartz-task/quartz-task-history-info-ins", UPDJson);


						//	rtn.msg += (bak + ";");
						//	rtn.code = 0;
						//}
					}
				}
			}
			catch (Exception e)
			{

				WriteLog("合格品不合格品调拨  组织" + it.Org + "  报错信息：" + e.Message, "HLMessge");
			}
			return rtn;
		}

		public class CreateTransferDocAfterFixDTO
		{
			public string Org { get; set; }

			public string Token { get; set; } = "";

		}

		[HttpPost]
		public Result<List<EDI_PODto>> EDIPOQuery(EDIPOQueryDTO req)
		{

			Result<List<EDI_PODto>> result = new Result<List<EDI_PODto>>();
			string sql = $@"select A.ID,C.Code AS OrgCode,D.Name as OrgName,A.Supplier_Code,A.DocNo,A.BusinessDate,B.IsPresent,B.DocLineNo,E.Name as CurrencyName,
B.ItemInfo_ItemCode,B.ItemInfo_ItemName,B.PurQtyPU,F.Name AS ItemUom,G.DeliveryDate
from PM_PurchaseOrder A
INNER JOIN PM_POLine B ON A.ID = B.PurchaseOrder
INNER JOIN Base_Organization C ON A.Org = C.ID
INNER JOIN Base_Organization_Trl D ON C.ID = D.ID AND D.SysMLFlag = 'zh-CN'
INNER JOIN Base_Currency_Trl E ON A.AC = E.ID AND E.SysMLFlag = 'zh-CN'
INNER JOIN Base_UOM_Trl F ON B.PriceUOM = F.ID AND F.SysMLFlag = 'zh-CN'
INNER JOIN PM_POShipLine G ON G.POLine = B.ID
where A.DescFlexField_PrivateDescSeg4 != 'True' and A.Status = 2";//时间限制为接口上线日，以前历史数据不管

			sql += $" and A.BusinessDate >= '{req.StartTime.Date}'";
			if (!string.IsNullOrEmpty(req.OrgCode))
			{
				sql += $" and C.Code = '{req.OrgCode}'";
			}
			DataSet ds = DbHelperSQL.Query(sql, connectionString);
			List<EDI_PODto> polineList = new List<EDI_PODto>();
			if (ds.Tables[0].Rows.Count > 0)
			{
				HashSet<long> polineSet = new HashSet<long>();
				foreach (DataRow poline in ds.Tables[0].Rows)
				{
					EDI_PODto dto = new EDI_PODto();
					dto.PURPOSE_CODE = "00";
					dto.FACILITY_ID = poline["OrgCode"].ToString();
					dto.SHIP_TO_ID = poline["OrgName"].ToString();
					dto.SUPPLIER_ID = poline["Supplier_Code"].ToString();
					dto.PO_NUMBER = poline["DocNo"].ToString();
					dto.PO_DATE = Convert.ToDateTime(poline["BusinessDate"]);
					dto.PO_GENERATION_DATE = Convert.ToDateTime(poline["BusinessDate"]);
					dto.TAX_EXEMPT_FLAG = Convert.ToBoolean(poline["IsPresent"]) ? "Y" : "N";
					dto.DISCOUNT_RATE = "N";
					dto.TOTAL_COST = "N";
					dto.CURRENCY = poline["CurrencyName"].ToString();
					dto.CUST_PART_NO = poline["ItemInfo_ItemCode"].ToString();
					dto.CUST_PART_DESC = poline["ItemInfo_ItemName"].ToString();
					dto.QUANTITY = Convert.ToDecimal(poline["PurQtyPU"]);
					dto.UNIT_PRICE = "N";
					dto.ORDER_UOFM = poline["ItemUom"].ToString();
					dto.REQUIREMENT_DATE = Convert.ToDateTime(poline["DeliveryDate"]);
					dto.PO_LINE_NO = poline["DocLineNo"].ToString();
					polineList.Add(dto);
					polineSet.Add(Convert.ToInt64(poline["ID"]));
				}
				//读取后设置状态为1
				string updateSql = $@"update PM_PurchaseOrder set DescFlexField_PrivateDescSeg4 = 'True' where ID in ({string.Join(",", polineSet.ToArray())})";
				try
				{
					DbHelperSQL.ExecuteSql(updateSql, connectionString);
				}
				catch (Exception ex)
				{
					throw new Exception(ex.Message);
				}
			}
			result.code = 1;
			result.data = polineList;
			return result;
		}

		[HttpPost]
		public Result<List<EDI_PackDto>> EDIPackQuery(EDIPOQueryDTO req)
		{
			Result<List<EDI_PackDto>> result = new Result<List<EDI_PackDto>>();
			string sql = $@"select A.ID,C.Code AS OrgCode,A.Code AS PackageCode,D.Name AS PackageName,E.Code AS ItemCode,E.Name AS ItemName,B.DocLineNo,B.PackNo,
F.PackName,B.PacksPerUnit,G.Name AS Uom,B.Length,B.Width,B.Height
from CBO_PackageSchema A
INNER JOIN CBO_PackageSchema_Trl D ON A.ID = D.ID AND D.SysMLFlag = 'zh-CN'
INNER JOIN CBO_PackSchema B ON A.ID = B.PackageSchema
INNER JOIN CBO_PackSchema_Trl F ON B.ID = F.ID AND F.SysMLFlag = 'zh-CN'
INNER JOIN Base_Organization C ON A.Org = C.ID
INNER JOIN CBO_ItemMaster E ON A.Item = E.ID
INNER JOIN Base_UOM_Trl G ON B.Uom = G.ID AND G.SysMLFlag = 'zh-CN'
where A.DescFlexField_PrivateDescSeg1 != 'True' and A.Status = 2";
			if (!string.IsNullOrEmpty(req.OrgCode))
			{
				sql += $" and C.Code = '{req.OrgCode}'";
			}
			DataSet ds = DbHelperSQL.Query(sql, connectionString);
			List<EDI_PackDto> packList = new List<EDI_PackDto>();
			if (ds.Tables[0].Rows.Count > 0)
			{
				HashSet<long> packSet = new HashSet<long>();
				foreach (DataRow pack in ds.Tables[0].Rows)
				{
					EDI_PackDto dto = new EDI_PackDto();
					dto.OrgCode = pack["OrgCode"].ToString();
					dto.PackageCode = pack["PackageCode"].ToString();
					dto.PackageName = pack["PackageName"].ToString();
					dto.ItemCode = pack["ItemCode"].ToString();
					dto.ItemName = pack["ItemName"].ToString();
					dto.DocLineNo = pack["DocLineNo"].ToString();
					dto.PackNo = pack["PackNo"].ToString();
					dto.PackName = pack["PackName"].ToString();
					dto.PacksPerUnit = Convert.ToDecimal(pack["PacksPerUnit"]);
					dto.Uom = pack["Uom"].ToString();
					dto.Length = Convert.ToDecimal(pack["Length"]);
					dto.Width = Convert.ToDecimal(pack["Width"]);
					dto.Height = Convert.ToDecimal(pack["Height"]);
					packList.Add(dto);
					packSet.Add(Convert.ToInt64(pack["ID"]));
				}
				//读取后设置状态为1
				string updateSql = $@"update CBO_PackageSchema set DescFlexField_PrivateDescSeg1 = 'True' where ID in ({string.Join(",", packSet.ToArray())})";
				try
				{
					DbHelperSQL.ExecuteSql(updateSql, connectionString);
				}
				catch (Exception ex)
				{
					throw new Exception(ex.Message);
				}
			}
			result.code = 1;
			result.data = packList;
			return result;
		}


		public static long GuidToLongID()
		{
			byte[] buffer = Guid.NewGuid().ToByteArray();
			return BitConverter.ToInt64(buffer, 0);
		}
		public static string GetTimestamp()
		{
			TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);//ToUniversalTime()转换为标准时区的时间,去掉的话直接就用北京时间
																					//随机数
			string strRandomResult = NextRandom(1000, 3).ToString();

			string randonTime = (long)ts.TotalMilliseconds + strRandomResult;//13位当前时间戳+4位随机数
			return randonTime;
		}
		public static int NextRandom(int numSeeds, int length)
		{
			// Create a byte array to hold the random value.  
			byte[] randomNumber = new byte[length];
			// Create a new instance of the RNGCryptoServiceProvider.  
			System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
			// Fill the array with a random value.  
			rng.GetBytes(randomNumber);
			// Convert the byte to an uint value to make the modulus operation easier.  
			uint randomResult = 0x0;
			for (int i = 0; i < length; i++)
			{
				randomResult |= ((uint)randomNumber[i] << ((length - 1 - i) * 8));
			}
			return (int)(randomResult % numSeeds) + 1;
		}

		public void WriteLog(string msg, string doctype)
		{
			try
			{
				string ip;
				ip = "local";
				string logFile = doctype;
				System.IO.StreamWriter sw = System.IO.File.AppendText(
					AppDomain.CurrentDomain.BaseDirectory + @"log\" + "debug_" + logFile + "_" +
					DateTime.Now.ToString("yyyyMMddHH") + ".Log"
					);
				sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + "from:" + ip + " " + msg);
				sw.Close();
			}
			catch
			{ }
		}


		/// <summary>
		/// DES数据解密
		/// </summary>
		/// <param name="targetValue"></param>
		/// <param name="key"></param>
		/// <returns></returns>
		public static string Decrypt(string targetValue, string key)
		{
			if (string.IsNullOrEmpty(targetValue))
			{
				return string.Empty;
			}
			// 定义DES加密对象
			var des = new DESCryptoServiceProvider();
			int len = targetValue.Length / 2;
			var inputByteArray = new byte[len];
			int x, i;
			for (x = 0; x < len; x++)
			{
				i = Convert.ToInt32(targetValue.Substring(x * 2, 2), 16);
				inputByteArray[x] = (byte)i;
			}
			// 通过两次哈希密码设置对称算法的初始化向量   
			des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
													(FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").
														Substring(0, 8), "sha1").Substring(0, 8));
			// 通过两次哈希密码设置算法的机密密钥   
			des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
													(FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")
														.Substring(0, 8), "md5").Substring(0, 8));
			// 定义内存流
			var ms = new MemoryStream();
			// 定义加密流
			var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
			cs.Write(inputByteArray, 0, inputByteArray.Length);
			cs.FlushFinalBlock();
			return Encoding.Default.GetString(ms.ToArray());
		}

	}
}
